<template>
  <div
    class="app-container"
    style="position: relative; height: calc(100vh - 117px)"
  >
    <div class="container">
      <el-tabs v-model="status" type="card" @tab-click="handleOrder">
        <el-tab-pane name="-9">
          <span slot="label"><i class="el-icon-s-order"></i> 全部订单</span>
        </el-tab-pane>
        <el-tab-pane name="0">
          <span slot="label"><i class="el-icon-bank-card"></i> 未支付</span>
        </el-tab-pane>
        <el-tab-pane name="1">
          <span slot="label"><i class="el-icon-refrigerator"></i> 未发货</span>
        </el-tab-pane>
        <el-tab-pane name="2">
          <span slot="label"><i class="el-icon-truck"></i> 待收货</span>
        </el-tab-pane>
        <el-tab-pane name="3">
          <span slot="label"><i class="el-icon-document"></i> 待评价</span>
        </el-tab-pane>
        <el-tab-pane name="4">
          <span slot="label"><i class="el-icon-circle-check"></i> 交易完成</span>
        </el-tab-pane>
      </el-tabs>
      <el-tabs v-model="payTypeL" type="card" @tab-click="handleOrder">
        <el-tab-pane name="yue">
          <span slot="label"><i class="el-icon-finished"></i> 社区店</span>
        </el-tab-pane>
        <el-tab-pane name="jifen">
          <span slot="label"><i class="el-icon-back"></i> 个人</span>
        </el-tab-pane>
      </el-tabs>
      <!--工具栏-->
      <div class="head-container">
        <!-- 搜索 -->
        <el-input
          v-model="query.value"
          clearable
          placeholder="输入搜索内容"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="toQuery"
        />
        <el-select
          v-model="query.type"
          clearable
          placeholder="类型"
          class="filter-item"
          style="width: 130px"
        >
          <el-option
            v-for="item in queryTypeOptions"
            :key="item.key"
            :label="item.display_name"
            :value="item.key"
          />
        </el-select>
       
        <el-date-picker
          v-model="createTime"
          :default-time="['00:00:00', '23:59:59']"
          type="daterange"
          range-separator=":"
          size="small"
          class="date-item"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
        <el-button
          class="filter-item"
          size="mini"
          type="success"
          icon="el-icon-search"
          @click="toQuery"
          >搜索</el-button
        >
        <el-button
          type="danger"
          class="filter-item"
          size="mini"
          icon="el-icon-refresh"
          @click="toQuery"
          >刷新</el-button
        >
      </div>
      <!--表格渲染-->
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="data"
        size="small"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column :selectable="checkboxT" type="selection" width="50" />
        <el-table-column prop="orderId" width="180" label="订单号">
          <template slot-scope="scope">
            <span>{{ scope.row.orderId }}</span>
            <p>[{{ typeL }}]</p>
          </template>
        </el-table-column>
        <el-table-column prop="realName" width="100" label="用户昵称">
          <template slot-scope="scope">
            <span>{{ scope.row.realName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="userPhone" label="购买者手机号" />
         <el-table-column prop="totalNum" label="商品数" />
        <el-table-column prop="payPrice" label="实际支付" />
        <el-table-column prop="paid" label="支付状态">
          <template slot-scope="scope">
            {{ paidFilter[scope.row.paid] }}
          </template>
        </el-table-column>
        <!--
            <el-table-column prop="payType" label="支付类型" >
        <template slot-scope="scope">
        {{payFilter[scope.row.payType]}}
        </template>
        </el-table-column>
        -->
        <el-table-column prop="status" label="订单状态">
          <template slot-scope="scope">
            <span>{{ statusFilter[scope.row.status] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="addTime" width="160" label="创建时间">
          <template slot-scope="scope">
            <span>{{ formatTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="addTime" width="160" label="支付时间">
          <template slot-scope="scope">
            <span>{{ formatTime(scope.row.payTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="examine(scope.row)">
              订单详情</el-button
            >
            <el-dropdown
              size="mini"
              split-button
              type="primary"
              trigger="click"
              v-show="scope.row.status == 1 && payTypeL == 'yue'"
            >
              操作
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button
                    size="mini"
                    type="primary"
                    @click="edit(scope.row)"
                  >
                    去发货</el-button
                  >
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    size="mini"
                    type="primary"
                    @click="refund(scope.row)"
                  >
                    拒单</el-button
                  >
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--添加订单打印及订单导出功能 2020.04.13 changxh-->
    <el-footer class="footer-contains">
      <div class="footer-search">
        <el-checkbox
          v-model="printChecked"
          @change="batchSelection"
          style="margin-right: 20px"
        ></el-checkbox>
        <el-select
          v-model="batchHandle"
          @change="handlePrintOption"
          clearable
          placeholder="批量操作"
          class="filter-item"
          style="width: 130px; margin-right: 8px"
        >
          <el-option
            v-for="item in handleOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="batchExport"
          @change="handleExportOption"
          clearable
          placeholder="批量导出"
          class="filter-item"
          style="width: 130px"
        >
          <el-option
            v-for="item in exportOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <!--分页组件-->
      <el-pagination
        :total="total"
        :current-page="page + 1"
        style="margin-top: 8px"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChange"
        @current-change="pageChange"
      />
      <el-dialog
        title="订单详情"
        :visible.sync="dialogVisible"
        append-to-body
        width="65%"
        height="40%"
      >
        <D ref="dto" :is-add="isAdd" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
    </el-footer>
  </div>
</template>

<script>
import initData from "@/mixins/crud";
import { del } from "@/api/yxStoreOrder";
import { formatTime } from "@/utils/index";
import { getYxStoreOrderDetail } from "@/api/yxStoreOrder";
import D from "../products/detail";
export default {
  components: { D },
  mixins: [initData],
  data() {
    return {
      typeL: "余额订单",
      order: {},
      payTypeL: "yue",
      delLoading: false,
      dialogVisible: false,
      status: "-9",
      orderType: "0",
      createTime: "",
      checkList: [],
      printChecked: false,
      batchHandle: "",
      batchExport: "",
      payType: "2",
      storeId: JSON.parse(localStorage.getItem("SET_USER")).retail,
      queryTypeOptions: [
        { key: "orderId", display_name: "订单号" },
        { key: "realName", display_name: "用户姓名" },
        { key: "userPhone", display_name: "用户电话" },
      ],
      statusOptions: [
        { value: "0", label: "未支付" },
        { value: "1", label: "未发货" },
        { value: "2", label: "待收货" },
        { value: "3", label: "待评价" },
        { value: "4", label: "交易完成" },
        // { value: '5', label: '待核销' },
        { value: "-1", label: "退款中" },
        { value: "-2", label: "已退款" },
        { value: "-4", label: "已删除" },
      ],
      statusFilter: ["待发货", "已发货", "已收货", "已完成"],
      payFilter: ["积分支付", "余额支付"],
      paidFilter: ["未支付", "已支付"],
      typeOptions: [
        { value: "0", label: "所有订单" },
        { value: "1", label: "普通订单" },
        { value: "2", label: "拼团订单" },
        { value: "3", label: "秒杀订单" },
        { value: "4", label: "砍价订单" },
      ],
      handleOptions: [
        { value: "", label: "批量操作" },
        { value: "0", label: "批量打印" },
      ],
      exportOptions: [
        { value: "", label: "批量导出" },
        { value: "0", label: "导出全部" },
        { value: "1", label: "导出选中" },
      ],
      caculateInfo: {
        orderNum: 0,
        storeNum: 0,
        orderPrice: 0,
        userNum: 0,
      },
    };
  },
  created() {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    formatStatus(value) {
      if (value === undefined || value === null || value === "") {
        return value;
      } else if (value == 0) {
        return "未支付";
      } else if (value == 1) {
        return "待发货";
      } else if (value == 2) {
        return "已发货";
      } else if (value == 3) {
        return "已收货";
      } else if (value == 4) {
        return "已完成";
      }
    },
    formatTime,
    handleOrder(tab, event) {
      if (tab.name === "jifen") {
        this.payType = "1";
        this.payTypeL = "jifen";
        this.typeL = "积分订单";
      } else if (tab.name === "yue") {
        this.payType = "2";
        this.payTypeL = "yue";
        this.typeL = "余额订单";
      } else {
        this.status = tab.name;
      }
      this.toQuery();
    },
    beforeInit() {
      this.url = "retail/order/yxStoreOrders";
      const sort = "id,desc";
      this.params = {
        page: this.page,
        size: this.size,
        sort: sort,
        orderStatus: this.status,
        orderType: this.orderType,
        createTime: this.createTime,
        storeId: this.storeId,
        payType: this.payType,
      };
      const query = this.query;
      const type = query.type;
      const value = query.value;
      if (type && value) {
        this.params[type] = value;
      }
      return true;
    },
    subDelete(id) {
      this.delLoading = true;
      del(id)
        .then((res) => {
          this.delLoading = false;
          this.$refs[id].doClose();
          this.dleChangePage();
          this.init();
          this.$notify({
            title: "删除成功",
            type: "success",
            duration: 2500,
          });
        })
        .catch((err) => {
          this.delLoading = false;
          this.$refs[id].doClose();
          console.log(err.response.data.message);
        });
    },
    add() {
      this.isAdd = true;
      this.$refs.form.dialog = true;
    },
    getDeatil(value) {},
    examine(data) {
      let products = [];
      let item = {};
      //获取详情数
      getYxStoreOrderDetail(data).then((resp) => {
        //成功获取数据的操作
        if (resp.length > 0) {
          resp.forEach((re) => {
            re.num = re.amount;
            products.push(re);
          });
          Object.assign(item, resp[0]);
        }
        this.dialogVisible = true;
        this.$nextTick(() => {
          const _this = this.$refs.dto;
          _this.order = {
            statusName: this.formatStatus(item.status),
            _status: 3,
            status: item.status,
            userPhone: item.userPhone,
            realName: item.realName,
            userAddress: item.userAddress,
            type: item.type,
            storeId: item.storeId,
            orderId: item.orderId, //虚拟单号
            payType: item.payType,
            shippingType: item.shippingType, //快递类型 可选择
            products: products,
            mark: item.mark,
            remark: item.mark,
            payPostage: 0,
            payPrice: item.totalPrice,
            totalPrice: item.totalPrice,
            couponPrice: 0,
            deductionPrice: 0.0, //积分折扣
          };
          _this.userDTO = {
            nickname: item.nickname,
          };
          this.isAdd = true;
        });
      });
    },
    edit(data) {
      console.log(data);
      this.$confirm(`确定进行[发货]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // onsale(id, { status: status }).then(({ data }) => {
          this.$message({
            message: "发货成功",
            type: "success",
            duration: 1000,
            onClose: () => {
              this.init();
            },
          });
          // });
        })
        .catch(() => {});
    },
    refund(data) {
      console.log(data);
      this.$confirm(`确定进行[拒单]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // onsale(id, { status: status }).then(({ data }) => {
          this.$message({
            message: "拒单成功",
            type: "success",
            duration: 1000,
            onClose: () => {
              this.init();
            },
          });
          // });
        })
        .catch(() => {});
    },
    clearCaculateInfo() {
      this.caculateInfo = {
        orderPrice: 0,
        storeNum: 0,
        orderNum: 0,
        userNum: 0,
      };
    },
    handleSelectionChange(val) {
      this.checkList = val;
      let orderPrice = 0,
        storeNum = 0,
        orderNum = 0,
        userNum = 0;
      if (val.length != 0) {
        this.printChecked = true;
        let user = [];
        val.forEach((item, index) => {
          orderNum += 1;
          orderPrice += item.totalPrice;
          storeNum += item.totalNum;
          user.push(item.userDTO.nickname);
        });
        user = Array.from(new Set(user));
        this.caculateInfo = {
          orderPrice: orderPrice.toFixed(2),
          storeNum: storeNum,
          orderNum: orderNum,
          userNum: user.length,
        };
      } else {
        this.printChecked = false;
        this.clearCaculateInfo();
        // this.getCaculateInfo();
      }
    },
    batchSelection(val) {
      let rows = this.data;
      if (val) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handlePrintOption(val) {
      switch (val) {
        case "0":
          this.getPrintList();
          this.batchHandle = "";
          break;
        default:
          break;
      }
    },
    handleExportOption(val) {
      let list = this.checkList;
      this.page = 0;
      this.size = 10000;
      switch (val) {
        case "0":
          this.listContent = "";
          this.beforeInit();
          this.downloadMethod();
          break;
        case "1":
          if (list.length == 0) {
            this.$message({
              message: "请选择订单",
              type: "warning",
            });
          } else {
            this.listContent = [];
            list.forEach((item) => {
              this.listContent.push(item.orderId);
            });
            this.listContent = JSON.stringify(this.listContent);
            this.beforeInit();
            this.downloadMethod();
          }
          break;
        default:
          break;
      }
      this.batchExport = "";
    },
    getPrintList() {
      let list = this.checkList;
      if (list.length == 0) {
        this.$message({
          message: "请选择订单",
          type: "warning",
        });
      } else {
        const _this = this.$refs.form5;
        _this.dialog = true;
      }
    },
    checkboxT(row, rowIndex) {
      return row.id !== 1;
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  height: calc(100% - 80px);
  position: absolute;
  overflow: auto;
  width: calc(100% - 20px);

  .order-caculate {
    font-size: 14px;
    color: #909399;
    border-top: 1px solid #f0f0f0;
    padding: 20px 10px;
    .caculate-title {
      display: inline-block;
      margin-right: 50px;
    }
    .caculate-num {
      font-size: 20px;
      color: #ff4949;
    }
  }

  .el-table th {
    background-color: #fafafa;
  }
}

.footer-contains {
  position: absolute;
  display: -ms-flexbox;
  display: flex;
  background-color: #f6f6f6;
  bottom: 0;
  flex-align: center;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  z-index: 999;
  padding: 0 20px 0 13px;
}

/*打印单样式编辑*/
.order-list {
  /*  height: 297mm;*/
  margin: 0 auto;
  width: 210mm;

  .order-title {
    height: 16mm;
    line-height: 16mm;
    font-size: 8mm;
    font-weight: bolder;
    text-align: center;
  }
  .order-info {
    span {
      display: inline-block;
      padding: 0 0 10px 0;
      font-size: 3mm;
    }
    span.info {
      width: 60mm;
    }
  }
  .el-table--small th,
  .el-table--small td {
    padding: 4px 0;
  }
}
</style>
